package com.cspg.design.request;

import android.util.Log;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.cspg.design.bean.UserInfo;
import com.cspg.design.common.Constant;
import com.cspg.design.dto.AuthUserDto;
import com.cspg.design.dto.ElectrifiedData;
import com.cspg.design.dto.ProjectDto;
import com.cspg.design.dto.ProjectFilePath;
import com.cspg.design.dto.ProjectInformation;
import com.cspg.design.dto.ProjectParameter;
import com.cspg.design.dto.ProjectProcessInformation;
import com.cspg.design.http.IService;
import com.cspg.design.http.ReslutVo;
import com.cspg.design.http.RetrofitUtil;
import com.cspg.design.http.RetrofitUtilDesign;
import com.cspg.design.model.PointDevicesModel;
import com.cspg.design.model.PolylineDevicesModel;
import com.cspg.design.model.ResponseResult;
import com.cspg.design.model.UserEIModel;
import com.cspg.design.model.UserModel;
import com.cspg.design.presenter.ProjectPresenter;
import com.cspg.design.utils.RSAUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.content.ContentValues.TAG;

public class Project {

    private RetrofitUtil retrofitUtil = new RetrofitUtil();
    private Call call;
    private ProjectPresenter presenter;
    private static final String type = "android";

    public Project(ProjectPresenter presenter) {
        this.presenter = presenter;
    }


    public void getProjectInformation(  String ProjectID) throws Exception
    {

        call = retrofitUtil.createReq(IService.class).projectInformation(ProjectID);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                if (null == response) {
                    presenter.httpRequestFailure(Constant.HTTP_NO_NET_WORK);
                    return;
                }

                if (!response.isSuccessful()) {
                    presenter.httpRequestFailure(Constant.HTTP_NO_NET_WORK);
                    return;
                }
                Object obj = response.body();
                if (obj == null)
                {
                    presenter.httpRequestFailure(Constant.HTTP_LOGIN_FAILURE);
                    return;
                }
                ProjectInformation projectInformation= (ProjectInformation) response.body();
                if (null == projectInformation) {
                    presenter.httpRequestFailure(Constant.HTTP_LOGIN_FAILURE);
                }
                else
                {
                    presenter.projectInfoHttpRequestSuccess(projectInformation);
                }
            }
            @Override
            public void onFailure(Call call, Throwable t) {
                presenter.httpRequestFailure("获取数据失败");
            }
        });
    }

    public void getGetProjectTerrain(  String ProjectID) throws Exception
    {

        call = retrofitUtil.createReq(IService.class).projectParameter(ProjectID);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                if (null == response) {
                    presenter.httpRequestFailure(Constant.HTTP_NO_NET_WORK);
                    return;
                }

                if (!response.isSuccessful()) {
                    presenter.httpRequestFailure(Constant.HTTP_NO_NET_WORK);
                    return;
                }
                Object obj = response.body();
                if (obj == null)
                {
                    presenter.httpRequestFailure(Constant.HTTP_LOGIN_FAILURE);
                    return;
                }
                List<ProjectParameter> projectParameters = (List<ProjectParameter>) response.body();
                if (null == projectParameters) {
                    presenter.httpRequestFailure(Constant.HTTP_LOGIN_FAILURE);
                }
                else if (projectParameters.size()==0)
                {
                    presenter.httpRequestFailure("没有查询到数据");
                }
                else
                {
                    presenter.projectParameterHttpRequestSuccess(projectParameters.get(0));
                }
            }
            @Override
            public void onFailure(Call call, Throwable t) {
                presenter.httpRequestFailure("获取数据失败");
            }
        });
    }

    public void getGetProjectFilePath(  String ProjectID , int UserRight) throws Exception
    {
        call = retrofitUtil.createReq(IService.class).projectProjectFilePath(ProjectID,UserRight);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                if (null == response) {
                    presenter.httpRequestFailure(Constant.HTTP_NO_NET_WORK);
                    return;
                }

                if (!response.isSuccessful()) {
                    presenter.httpRequestFailure(Constant.HTTP_NO_NET_WORK);
                    return;
                }
                Object obj = response.body();
                if (obj == null)
                {
                    presenter.httpRequestFailure(Constant.HTTP_LOGIN_FAILURE);
                    return;
                }
                List<ProjectFilePath> projectFilePathList = (List<ProjectFilePath>) response.body();
                if (null == projectFilePathList) {
                    presenter.httpRequestFailure(Constant.HTTP_LOGIN_FAILURE);
                }
                else if (projectFilePathList.size()==0)
                {
                    presenter.httpRequestFailure("没有查询到数据");
                }
                else
                {
                    presenter.projectFilePathHttpRequestSuccess(projectFilePathList);
                }
            }
            @Override
            public void onFailure(Call call, Throwable t) {
                presenter.httpRequestFailure("获取数据失败");
            }
        });
    }

    public void  getGetProjectFile(String FilePath,String contentType) throws Exception
    {

        Log.e("FilePath",FilePath);
        call = retrofitUtil.createReq(IService.class).projectProjectFile(FilePath,contentType);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                if (null == response) {
                    presenter.httpRequestFailure(Constant.HTTP_NO_NET_WORK);
                    return;
                }

                if (!response.isSuccessful()) {
                    presenter.httpRequestFailure(Constant.HTTP_NO_NET_WORK);
                    return;
                }
                Object obj = response.body();
                if (obj == null)
                {
                    presenter.httpRequestFailure(Constant.HTTP_LOGIN_FAILURE);
                    return;
                }
                else
                {
                    presenter.projectFileHttpRequestSuccess((ResponseBody) obj);
                }
            }
            @Override
            public void onFailure(Call call, Throwable t) {
                presenter.httpRequestFailure("获取数据失败");
            }
        });
    }

    public void  getProjectSubmit(String ProjectID, String EmployeeID, boolean Result , String Remark ) throws Exception
    {
        call = retrofitUtil.createReq(IService.class).projectSubmit( ProjectID,  EmployeeID,  Result ,  Remark );
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                if (null == response) {
                    presenter.httpRequestFailure(Constant.HTTP_NO_NET_WORK);
                    return;
                }

                if (!response.isSuccessful()) {
                    presenter.httpRequestFailure(Constant.HTTP_NO_NET_WORK);
                    return;
                }
                Object obj = response.body();
                if (obj == null)
                {
                    presenter.httpRequestFailure(Constant.HTTP_LOGIN_FAILURE);
                    return;
                }
                ResponseResult responseResult = (ResponseResult) response.body();
                if (null == responseResult) {
                    presenter.httpRequestFailure(Constant.HTTP_LOGIN_FAILURE);
                }
                else if (responseResult.getResult() != 1)
                {
                    presenter.httpRequestFailure("提交失败");
                }
                else
                {
                    presenter.httpRequestSuccess();
                }
            }
            @Override
            public void onFailure(Call call, Throwable t) {
                presenter.httpRequestFailure("获取数据失败");
            }
        });
    }

    public void  getProjectFlow(String ProjectID) throws Exception
    {
        call = retrofitUtil.createReq(IService.class).projectFlow( ProjectID);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                if (null == response) {
                    presenter.httpRequestFailure(Constant.HTTP_NO_NET_WORK);
                    return;
                }

                if (!response.isSuccessful()) {
                    presenter.httpRequestFailure(Constant.HTTP_NO_NET_WORK);
                    return;
                }
                try {
                    Object obj = response.body();
                    List<ProjectProcessInformation> list = (List<ProjectProcessInformation>) obj;
                    if (obj == null)
                    {
                        presenter.httpRequestFailure(Constant.HTTP_LOGIN_FAILURE);
                        return;
                    }
                    else
                    {
                        presenter.projectFlowHttpRequestSuccess(list);
                    }
                }catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
            @Override
            public void onFailure(Call call, Throwable t) {
                presenter.httpRequestFailure("获取数据失败");
            }
        });
    }

    public void  postProjectElectrifiedSubmit(String ProjectID, String electrifiedData) throws Exception
    {
        call = retrofitUtil.createReq(IService.class).projectGetElectrifiedSubmit(ProjectID,electrifiedData);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                if (null == response) {
                    presenter.httpRequestFailure(Constant.HTTP_NO_NET_WORK);
                    return;
                }

                if (!response.isSuccessful()) {
                    presenter.httpRequestFailure(Constant.HTTP_NO_NET_WORK);
                    return;
                }
                try {
                    Object obj = response.body();
                    if (obj == null)
                    {
                        presenter.httpRequestFailure(Constant.HTTP_LOGIN_FAILURE);
                        return;
                    }
                    else
                    {
                        ResponseResult responseResult = (ResponseResult) obj;
                        if (responseResult == null || responseResult.getResult() != 1)
                        {
                            presenter.getFailure("提交失败。。。");
                        }
                        else
                        {
                            presenter.httpRequestSuccess();
                        }
                    }
                }catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
            @Override
            public void onFailure(Call call, Throwable t) {
                presenter.httpRequestFailure("获取数据失败");
            }
        });
    }

    public void  getProjectDevice(String ProjectID) throws Exception
    {
        String username = "admin";
        String pwd = "123456";
        String encode_result = RSAUtils.encryptDataStr(pwd.getBytes(), RSAUtils.loadPublicKey(Constant.publicKey));
        AuthUserDto authUserDto = new AuthUserDto();
        authUserDto.setUsername(username);
        authUserDto.setPassword(encode_result);

        RetrofitUtilDesign retrofitUtilDesign = new RetrofitUtilDesign();
        call = retrofitUtilDesign.createReq(IService.class).login(authUserDto);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                if (null == response) {
                    presenter.httpRequestFailure(Constant.HTTP_NO_NET_WORK);
                    return;
                }

                if (!response.isSuccessful()) {
                    presenter.httpRequestFailure(Constant.HTTP_NO_NET_WORK);
                    return;
                }
                try {
                    Object obj = response.body();
                    UserEIModel userModel= (UserEIModel) response.body();
                    if (null == userModel) {
                        presenter.httpRequestFailure(Constant.HTTP_NO_NET_WORK);
                        return;
                    }
                    else
                    {
                        String token = userModel.getToken();
                        UserInfo userInfo = UserInfo.getInstance();
                        userInfo.token = token;
                        UserInfo.setUserInfo(userInfo);
                        getPointDeviceByProjectId(ProjectID);
                        getPolylineDeviceByProjectId(ProjectID);
                    }
                }catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
            @Override
            public void onFailure(Call call, Throwable t) {
                presenter.httpRequestFailure("获取数据失败");
            }
        });
    }

    public void getPointDeviceByProjectId(String projectId)
    {
        RetrofitUtilDesign retrofitUtil = new RetrofitUtilDesign();
        call = retrofitUtil.createReq(IService.class).getPointDeviceByProjectId(0,1000,projectId);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                if (null == response) {
                    presenter.getFailure(Constant.HTTP_NO_NET_WORK);
                    return;
                }
                if (!response.isSuccessful()) {
                    presenter.getFailure(Constant.HTTP_NO_NET_WORK);
                    return;
                }
                Object obj = response.body();
                PointDevicesModel pointDevicesModel = (PointDevicesModel) response.body();
                if (null == pointDevicesModel) {
                    presenter.getFailure(Constant.HTTP_REQUEST_NET_WORK_ERROR);
                    return;
                }
                else
                {
                    presenter.requestSuccessPoints(pointDevicesModel.getContent(),1);
                }
            }
            @Override
            public void onFailure(Call call, Throwable t) {
                presenter.getFailure(Constant.HTTP_NO_NET_WORK);
            }
        });
    }

    public void getPolylineDeviceByProjectId(String projectId)
    {
        RetrofitUtilDesign retrofitUtil = new RetrofitUtilDesign();
        call = retrofitUtil.createReq(IService.class).getPolylineDeviceByProjectId(0,1000,projectId);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                if (null == response) {
                    presenter.getFailure(Constant.HTTP_NO_NET_WORK);
                    return;
                }
                if (!response.isSuccessful()) {
                    presenter.getFailure(Constant.HTTP_NO_NET_WORK);
                    return;
                }
                Object obj = response.body();
                PolylineDevicesModel polylineDevicesModel = (PolylineDevicesModel) response.body();
                if (null == polylineDevicesModel) {
                    presenter.getFailure(Constant.HTTP_REQUEST_NET_WORK_ERROR);
                }
                else
                {
                    presenter.requestSuccessPolylines(polylineDevicesModel.getContent(),1);
                }
            }
            @Override
            public void onFailure(Call call, Throwable t) {
                presenter.getFailure(Constant.HTTP_NO_NET_WORK);
            }
        });
    }


    public RequestBody getRequestBody(HashMap<String, String> hashMap) {
        StringBuffer data = new StringBuffer();
        if (hashMap != null && hashMap.size() > 0) {
            Iterator iter = hashMap.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                Object key = entry.getKey();
                Object val = entry.getValue();
                data.append(key).append("=").append(val).append("&");
            }
        }
        String jso = data.substring(0, data.length() - 1);
        RequestBody requestBody =
                RequestBody.create(MediaType.parse("application/json;charset=UTF-8"),jso);

        return requestBody;
    }

    public void getProject(String EmployeeID) throws Exception
    {
        RetrofitUtil retrofitUtil = new RetrofitUtil();
        call = retrofitUtil.createReq(IService.class).project(EmployeeID);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                if (null == response) {
                    presenter.getFailure(Constant.HTTP_NO_NET_WORK);
                    return;
                }
                if (response.code() == 401)
                {
                    presenter.getTokenExpireFailure();
                    return;
                }

                if (!response.isSuccessful()) {
                    presenter.getFailure(Constant.HTTP_NO_NET_WORK);
                    return;
                }
                Object obj = response.body();
                List<ProjectDto> projectDtos= (List<ProjectDto>) response.body();
                if (null == projectDtos) {
                    presenter.getFailure("没有待办数据。。。。");
                }
                else
                {
                    presenter.projectRequestSuccess(projectDtos);
                }
            }
            @Override
            public void onFailure(Call call, Throwable t) {
                presenter.getFailure(Constant.HTTP_NO_NET_WORK);
            }
        });
    }

    public void getProjectHistory(String EmployeeID) throws Exception
    {
        RetrofitUtil retrofitUtil = new RetrofitUtil();
        call = retrofitUtil.createReq(IService.class).projectHistory(EmployeeID);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                if (null == response) {
                    presenter.getFailure(Constant.HTTP_NO_NET_WORK);
                    return;
                }
                if (response.code() == 401)
                {
                    presenter.getTokenExpireFailure();
                    return;
                }

                if (!response.isSuccessful()) {
                    presenter.getFailure(Constant.HTTP_NO_NET_WORK);
                    return;
                }
                List<ProjectDto> projectDtos= (List<ProjectDto>) response.body();
                if (null == projectDtos) {
                    presenter.getFailure("没有数据。。。。");
                }
                else
                {
                    presenter.projectHistoryRequestSuccess(projectDtos);
                }
            }
            @Override
            public void onFailure(Call call, Throwable t) {
                presenter.getFailure(Constant.HTTP_NO_NET_WORK);
            }
        });
    }

}
